import { useMemoizedFn } from 'ahooks';
import { Radio, RadioChangeEvent } from 'antd';
import {
    Cartesian2,
    Cartesian3,
    ImageMaterialProperty,
    Rectangle,
    RectangleGraphics,
} from 'cesium';
import { useEffect, useRef, useState } from 'react';
import { Entity, useCesium } from 'resium';
import videoMp4 from '../../../../assets/video/meinv.mp4';
import { useAppSelector } from '../../../../store';

export default function BackgroundVideo() {
    const { viewer } = useCesium();
    const videoRef = useRef<HTMLVideoElement>(null);
    const [value, setValue] = useState(3);
    const pos = useAppSelector((state) => state.scene.initPosition);

    const [rectangle, setRectangle] = useState<
        RectangleGraphics | RectangleGraphics.ConstructorOptions | undefined
    >();

    const update = useMemoizedFn((size) => {
        if (videoRef.current && viewer) {
            const videoElement = videoRef.current;
            videoElement.muted = true;
            videoElement.play();

            // 将视频元素作为矩形的材质.也就是将视频作为贴图
            const material = new ImageMaterialProperty({
                image: videoElement,
                repeat: new Cartesian2(size, size),
            });

            setRectangle({
                // 表示全球范围的矩形区域。该矩形的经度范围为-180到180度，纬度范围为-90到90度
                coordinates: Rectangle.fromDegrees(-180.0, -90.0, 180.0, 90.0),
                material: material,
            });

            viewer.camera.setView({
                destination: Cartesian3.fromDegrees(pos.longitude, pos.latitude, 20000000),
            });
        }
    });

    useEffect(() => {
        update(value);
    }, [update, value, viewer]);

    const onChange = useMemoizedFn((e: RadioChangeEvent) => {
        setValue(e.target.value);
    });

    return (
        <>
            <div
                style={{
                    position: 'absolute',
                    top: '50px',
                    left: '10px',
                }}
            >
                <Radio.Group value={value} buttonStyle="solid" onChange={onChange}>
                    <Radio.Button value={1}>x1</Radio.Button>
                    <Radio.Button value={3}>x3</Radio.Button>
                    <Radio.Button value={6}>x6</Radio.Button>
                </Radio.Group>
            </div>
            <video
                ref={videoRef}
                style={{ position: 'absolute', left: '10px', top: '90px', width: '300px' }}
                controls
                autoPlay
                loop
            >
                <source src={videoMp4} type="video/mp4" />
            </video>
            <Entity rectangle={rectangle} />
        </>
    );
}
